package com.zp.self.module.level_4_算法练习.算法.深度优先搜索.递归;

/**
 * @author By ZengPeng
 */
public class 力扣_200_岛屿数量 {
    //测试
    public static void main(String[] args) {

        System.out.println(new 力扣_200_岛屿数量().numIslands(new char[][]{
                {'1','1','1','1','0'},
                {'1','1','0','1','0'},
                {'1','1','0','0','0'},
                {'0','0','0','0','0'}}));
    }

    /**
    题目：给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
     岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
     此外，你可以假设该网格的四条边均被水包围。

     示例 1：
     输入：grid = [
     ["1","1","1","1","0"],
     ["1","1","0","1","0"],
     ["1","1","0","0","0"],
     ["0","0","0","0","0"]
     ]
     输出：1

     示例 2：
     输入：grid = [
     ["1","1","0","0","0"],
     ["1","1","0","0","0"],
     ["0","0","1","0","0"],
     ["0","0","0","1","1"]
     ]
     输出：3

    分析：【P 💙💜】
       1.递归： 找到岛屿,岛屿数+1，将岛屿的土地全部感染成水
                3步曲：单步操作--保证循环不变量
                      返回值
                      终止条件
                -- 执行用时：3 ms, 在所有 Java 提交中击败了63.32%的用户

    边界值 & 注意点：
       1.
     **/
    public int numIslands(char[][] grid) {
        int sum=0;
        for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if(grid[i][j]=='1'){
                dfs(grid,i,j);
                sum++;
            }
        }
    }
        return sum;
}

    private void dfs(char[][] grid, int x, int y) {
        if(x<0 || x==grid.length ||y<0 ||y==grid[0].length || grid[x][y]=='0')
            return;
        if(grid[x][y]=='1')
            grid[x][y]='0';
        dfs(grid,x+1,y);
        dfs(grid,x-1,y);
        dfs(grid,x,y+1);
        dfs(grid,x,y-1);
    }
}
